package org.mxp.demo9.refuse;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import org.mxp.utils.RabbitMQUtils;

import java.util.HashMap;
import java.util.Map;

public class ReceiveObj1 {
    public static void main(String[] args) throws Exception {
        // 普通交换机的名称
        String NORMAL_EXCHANGE = "normal_exchange";
        // 死信交换机的名称
        String DEAD_EXCHANGE = "dead_exchange";
        // 普通队列的名称
        String NORMAL_QUEUE = "normal_queue";
        // 死信队列的名称
        String DEAD_QUEUE = "dead_queue";

        // 获取信道
        Channel channel = RabbitMQUtils.getChannel();
        // 声明普通交换机，类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        // 构建普通队列参数
        Map<String,Object> arguments = new HashMap<>();
        // 正常的队列设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        // 设置死信routingKey
        arguments.put("x-dead-letter-routing-key", "lisi");

        // 声明普通队列，并接收参数，指定死信队列
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments).getQueue();
        // 绑定普通交换机与队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        // 普通队列接受消息
        channel.basicConsume(NORMAL_QUEUE, false, (consumerTag, message) -> {
            String msg = new String(message.getBody());
            if ("hello world 3".equals(msg)) {
                System.out.println(NORMAL_QUEUE + "拒绝消息：" + msg);
                // 否定确认，requeue设置为false，代表拒绝重新入队，该队列如果配置了死信交换机将发送到死信队列中
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println(NORMAL_QUEUE + "接受到消息：" + msg);
                // 确认
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
        }, (consumerTag) -> {});

        // 声明死信交换机，类型为direct
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        // 声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null).getQueue();
        // 绑定死信交换机与队列
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");
    }
}
